package com.test.springCloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.test.springCloud.mapper.MenuMapper;
import com.test.springCloud.service.MenuService;
import com.test.springcloud.pojo.MenuPojo;
import com.test.springcloud.pojo.RoleNavPojo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author luoxingfa
 * @createdate 2023/5/31 0031 11:11
 * @mood happy
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Resource
    MenuMapper menuMapper;
    @Override
    public String getMenu(Integer menu_id) {
        JSONObject js = new JSONObject();
        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }
    @Override
    public List<RoleNavPojo> getMenuRootByRoleId(Integer roleId) {
        return menuMapper.getMenuIdByRoleId(roleId);
    }

    @Override
    public String getRouterByUserId(Integer userId) {

        JSONObject js = new JSONObject();
        //只有主菜单
        List<MenuPojo> menusBase = menuMapper.getRouterByParentId(0);
        //所有的菜单
        List<MenuPojo> menuNotBase = menuMapper.getAllRouterNoBase();
        for (MenuPojo sysMenu : menusBase) {
            //返回主菜单的子菜单
            List<MenuPojo> menus = iterateMenus(menuNotBase, sysMenu.getMenuId());
            sysMenu.setChildren(menus);
        }
        if (menusBase.size()>0){
            js.put("code",200);
            js.put("msg","路由获取成功！");
            js.put("data",menusBase);
        }else {
            js.put("code",401);
            js.put("msg","路由获取失败！");
        }

        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }

    @Override
    public List<MenuPojo> iterateMenus(List<MenuPojo> menuPojoList, Integer menu_id) {
        List<MenuPojo> result = new ArrayList<>();
        //得到对象
        for (MenuPojo sysMenu : menuPojoList) {
            //获取菜单的id
            Integer menuIds = sysMenu.getMenuId();
            //获取菜单的父id
            String parentId = String.valueOf(sysMenu.getParentId());
            if (StringUtils.isNotBlank(parentId)) {
                if (parentId.equals(String.valueOf(menu_id))) {
                    //递归查询当前子菜单的子菜单
                    List<MenuPojo> iterateMenu = iterateMenus(menuPojoList, menuIds);
                    sysMenu.setChildren(iterateMenu);
                    result.add(sysMenu);
                }
            }
        }
        return result;
    }
}
